import type { InputProps } from 'antd';
import { Input } from 'antd';
import { ChangeEvent, FC, useLayoutEffect, useState } from 'react';
import OStyle from './index.less';

type PhoneInputPorps = Omit<InputProps, 'value'> & { value?: string };

const PhoneInput: FC<PhoneInputPorps> = ({ value, onChange, placeholder = '手机号码', ...params }) => {
  const [myValue, setMyValue] = useState<string | undefined>();

  const valueOnChange = (e: ChangeEvent<HTMLInputElement>) => {
    let value = e.target.value;
    value = value.replace(/[^\d]/g, '').substring(0, 11);
    value = `${value.substring(0, 3)} ${value.substring(3, 7)} ${value.substring(7)}`.trim();
    e.target.value = value.replaceAll(' ', '');
    onChange?.(e);
    setMyValue(value);
  };

  useLayoutEffect(() => {
    if (value) {
      value = value.replace(/[^\d]/g, '').substring(0, 11);
      value = `${value.substring(0, 3)} ${value.substring(3, 7)} ${value.substring(7)}`.trim();
    }
    setMyValue(value);
  }, [value]);

  return (
    <Input
      value={myValue}
      placeholder={placeholder}
      size="large"
      onChange={valueOnChange}
      bordered={false}
      prefix={
        <div className={OStyle.phone_icon}>
          <div></div>
          {myValue && <span>+86</span>}
        </div>
      }
      {...params}
    />
  );
};

export default PhoneInput;
